package br.com.lucasddaniel.merchanmobile.dao;

import java.util.Hashtable;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDiskIOException;
import br.com.lucasddaniel.merchanmobile.bean.ResponsavelBean;

/**
 * Classe de manipula�ao dos dados para enviar � persistencia.
 * 
 * @author ldsm
 * 
 */
public class ResponsavelRepositorio {

	/**
	 * Insere um ResponsavelBean na base.
	 * 
	 * @param resp
	 * @throws ExcessaoBanco
	 */
	public void inserir(ResponsavelBean resp, Context ctx) throws ExcessaoBanco {
		ContentValues cv = new ContentValues();
		cv.put(ResponsavelEsquemaBanco.TABLE_COLUMNS[1].getColumnName(), resp.getLogin());
		cv.put(ResponsavelEsquemaBanco.TABLE_COLUMNS[2].getColumnName(), resp.getSenha());

		try {
			ResponsavelAdaptadorBanco.insere(ResponsavelEsquemaBanco.TABLE_NAME, cv);
		} catch (SQLiteDiskIOException diskIOException) {
			throw new ExcessaoBanco("Memoria insuficiente para criar ou copiar itens.", ExcessaoBanco.INSUFFICIENT_MEMORY);
		} finally {
			ResponsavelAdaptadorBanco.fecha(true);
		}
	}

	/**
	 * Pesquisa um ResponsavelBean de acordo com o login e senha.
	 * 
	 * @param ResponsavelBean
	 * @return
	 * @throws ExcessaoBanco
	 */
	public ResponsavelBean buscar(ResponsavelBean resp, Context ctx) throws ExcessaoBanco {
		ResponsavelBean retorno = null;
		try {
			ResponsavelAdaptadorBanco.abre(ctx);
			Hashtable<String, String> filters = new Hashtable<String, String>();
			if (resp.getLogin() != null) {
				filters.put(ResponsavelEsquemaBanco.TABLE_COLUMNS[1].getColumnName(), "" + resp.getLogin());
			}
			if (resp.getSenha() != null) {
				filters.put(ResponsavelEsquemaBanco.TABLE_COLUMNS[2].getColumnName(), "" + resp.getSenha());
			}

			Cursor cursorResult = ResponsavelAdaptadorBanco.getObjects(ResponsavelEsquemaBanco.TABLE_NAME, filters);
			if (cursorResult.moveToFirst()) {
				retorno = new ResponsavelBean();
				retorno.setLogin(cursorResult.getString(cursorResult.getColumnIndex(ResponsavelEsquemaBanco.TABLE_COLUMNS[1].getColumnName())));
				retorno.setSenha(cursorResult.getString(cursorResult.getColumnIndex(ResponsavelEsquemaBanco.TABLE_COLUMNS[2].getColumnName())));
			}
			cursorResult.close();
		} catch (SQLiteDiskIOException diskIOException) {
			throw new ExcessaoBanco("Memoria insuficiente para criar ou copiar itens.", ExcessaoBanco.INSUFFICIENT_MEMORY);
		} finally {
			ResponsavelAdaptadorBanco.fecha(true);
		}
		return retorno;
	}
}
